package com.ruoyi.web.core.config;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.service.card.IGshCardService;
import com.ruoyi.util.GshQrcodeUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Map;

/**
 * TODO
 *
 * @author chenchuan2
 * @date 2024-04-05 22:20:42
 */
@Component
@Slf4j
public class TextHandler implements WxMpMessageHandler {

    @Autowired
    private IGshCardService gshCardService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        try {
            // 接收的消息内容
            String inContent = wxMessage.getContent();
            log.info("======TextHandler======[{}]", context);
//        // 响应的消息内容
//        String outContent;
//        // 根据不同的关键字回复消息
//        if (inContent.contains("游戏")){
//            outContent = "仙剑奇侠传";
//        }else if (inContent.contains("动漫")){
//            outContent = "进击的巨人";
//        }else {
//            outContent = inContent;
//        }
            if(inContent.equals("888888")){
                String cardMemberNo = gshCardService.gshCardMemberNo();
                String filePath = GshQrcodeUtil.generateQRCodeWithImage(cardMemberNo);
                WxMediaUploadResult wxMediaUploadResult = wxMpService.getMaterialService().mediaUpload(WxConsts.MaterialType.IMAGE, new File(filePath));
                log.info("wxMediaUploadResult[{}]", JSONObject.toJSONString(wxMediaUploadResult));
                // 构造响应消息对象
                return WxMpXmlOutMessage.IMAGE().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                        .mediaId(wxMediaUploadResult.getMediaId()).build();
            }else{
                return WxMpXmlOutMessage.TEXT().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                        .content("口令输入错误或已过期，请您发送正确数字口令！\n" +
                                "如果没有口令，请使用咸鱼付款，获取最新口令。\n" +
                                "【闲鱼】https://m.tb.cn/h.5zaNtsg?tk=UsbzWKtW6u2 CZ0001 「乌衣巷登山草莓的闲鱼号，快来关注TA吧～」\n" +
                                "点击链接直接打开").build();
            }
        } catch (Exception ex) {
            log.error("TextHandler error", ex);
        }
        return null;
    }


}
